# -*- coding:utf-8 -*-
# @FileName : app\api\v1\users\routes.py
# @Time     : 2025/11/28
# @Author   : 天空之城
"""用户模块路由文件

此模块定义用户相关的API路由，处理HTTP请求和响应。
"""
from flask import Blueprint, request
from app.utils.response_factory import ResponseFactory
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.api.v1.users.services import UserService, RoleService, PermissionService
from app.api.v1.users.schemas import UserSchema, RegisterCredentialsSchema, ForgotPasswordSchema
from app.config import logger

# 创建用户蓝图
users_bp = Blueprint('users', __name__)

# 初始化服务和模式
user_service = UserService()
role_service = RoleService()
permission_service = PermissionService()
user_schema = UserSchema()
users_schema = UserSchema(many=True)


@users_bp.route('/', methods=['GET'])
def get_users():
    """获取用户列表
    
    Returns:
        JSON格式的用户列表
    """
    users = user_service.get_all_users()
    return ResponseFactory.success(data=users_schema.dump(users))


@users_bp.route('/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取单个用户信息
    
    Args:
        user_id: 用户ID
    
    Returns:
        JSON格式的用户信息
    """
    user = user_service.get_user_by_id(user_id)
    if not user:
        return ResponseFactory.error(msg='User not found', code=404)
    return ResponseFactory.success(data=user_schema.dump(user))


@users_bp.route('/', methods=['POST'])
def create_user():
    """创建新用户
    
    Returns:
        JSON格式的新创建用户信息
    """
    data = request.get_json()
    # 验证数据
    errors = user_schema.validate(data)
    if errors:
        return ResponseFactory.error(msg='数据验证失败', code=400, errors=errors)
    
    user = user_service.create_user(data)
    return ResponseFactory.success(data=user_schema.dump(user), msg='用户创建成功', code=201)


@users_bp.route('/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    """更新用户信息
    
    Args:
        user_id: 用户ID
    
    Returns:
        JSON格式的更新后用户信息
    """
    data = request.get_json()
    # 验证数据
    errors = user_schema.validate(data, partial=True)
    if errors:
        return ResponseFactory.error(msg='数据验证失败', code=400, errors=errors)
    
    user = user_service.update_user(user_id, data)
    if not user:
        return ResponseFactory.error(msg='User not found', code=404)
    return ResponseFactory.success(data=user_schema.dump(user), msg='用户更新成功')


@users_bp.route('/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    """删除用户
    
    Args:
        user_id: 用户ID
    
    Returns:
        空响应
    """
    success = user_service.delete_user(user_id)
    if not success:
        return ResponseFactory.error(msg='User not found', code=404)
    return ResponseFactory.success(data=None, msg='用户删除成功', code=204)





@users_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前登录用户的个人资料
    
    Returns:
        JSON格式的用户信息
    """
    current_user_id = int(get_jwt_identity())
    user = user_service.get_user_by_id(current_user_id)
    
    if not user:
        return ResponseFactory.error(msg='User not found', code=404)
    
    return ResponseFactory.success(data=user_schema.dump(user), msg='获取个人资料成功')


@users_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    """获取当前登录用户信息（兼容前端/auth/me接口）
    
    Returns:
        JSON格式的用户信息
    """
    current_user_id = int(get_jwt_identity())
    user = user_service.get_user_by_id(current_user_id)
    
    if not user:
        return ResponseFactory.error(msg='User not found', code=404)
    
    return ResponseFactory.success(data=user_schema.dump(user), msg='获取用户信息成功')


@users_bp.route('/roles', methods=['POST'])
def create_role():
    """创建新角色
    
    Returns:
        JSON格式的新创建角色信息
    """
    data = request.get_json()
    role = role_service.create_role(data)
    return ResponseFactory.success(data={
        'id': role.id,
        'name': role.name,
        'description': role.description
    }, msg='角色创建成功', code=201)


@users_bp.route('/roles', methods=['GET'])
def get_roles():
    """获取角色列表
    
    Returns:
        JSON格式的角色列表
    """
    roles = role_service.get_all_roles()
    return ResponseFactory.success(data=[{
        'id': role.id,
        'name': role.name,
        'description': role.description
    } for role in roles], msg='获取角色列表成功')


@users_bp.route('/permissions', methods=['POST'])
def create_permission():
    """创建新权限
    
    Returns:
        JSON格式的新创建权限信息
    """
    data = request.get_json()
    permission = permission_service.create_permission(data)
    return ResponseFactory.success(data={
        'id': permission.id,
        'name': permission.name,
        'description': permission.description
    }, msg='权限创建成功', code=201)


@users_bp.route('/permissions', methods=['GET'])
def get_permissions():
    """获取权限列表
    
    Returns:
        JSON格式的权限列表
    """
    permissions = permission_service.get_all_permissions()
    return ResponseFactory.success(data=[{
        'id': permission.id,
        'name': permission.name,
        'description': permission.description
    } for permission in permissions], msg='获取权限列表成功')


@users_bp.route('/<int:user_id>/roles/<int:role_id>', methods=['POST'])
def assign_role(user_id, role_id):
    """为用户分配角色
    
    Args:
        user_id: 用户ID
        role_id: 角色ID
    
    Returns:
        成功或失败的消息
    """
    success = role_service.add_role_to_user(user_id, role_id)
    if success:
        return ResponseFactory.success(msg='Role assigned successfully')
    return ResponseFactory.error(msg='Failed to assign role', code=400)


@users_bp.route('/roles/<int:role_id>/permissions/<int:permission_id>', methods=['POST'])
def assign_permission(role_id, permission_id):
    """为角色分配权限
    
    Args:
        role_id: 角色ID
        permission_id: 权限ID
    
    Returns:
        成功或失败的消息
    """
    success = role_service.add_permission_to_role(role_id, permission_id)
    if success:
        return ResponseFactory.success(msg='Permission assigned successfully')
    return ResponseFactory.error(msg='Failed to assign permission', code=400)


@users_bp.route('/register', methods=['POST'])
def register():
    """用户注册
    
    Returns:
        JSON格式的用户信息和访问令牌
    """
    logger.info("收到用户注册请求")
    data = request.get_json()
    
    # 创建验证器
    register_schema = RegisterCredentialsSchema()
    
    # 验证数据
    errors = register_schema.validate(data)
    if errors:
        logger.warning(f"注册数据验证失败: {errors}")
        return ResponseFactory.error(msg='数据验证失败', code=400, errors=errors)
    
    # 检查密码确认
    if data['password'] != data['confirm_password']:
        logger.warning("密码和确认密码不匹配")
        return ResponseFactory.error(msg='密码和确认密码不匹配', code=400)
    
    try:
        # 注册用户
        user = user_service.register_user(data)
        
        # 创建JWT访问令牌
        access_token = create_access_token(identity=str(user.id))
        
        logger.info(f"用户注册成功，用户ID: {user.id}, 用户名: {user.username}")
        
        return ResponseFactory.success(data={
            'access_token': access_token,
            'user': user_schema.dump(user)
        }, msg='注册成功', code=201)
        
    except ValueError as e:
        logger.warning(f"用户注册失败，业务错误: {str(e)}")
        return ResponseFactory.error(msg=str(e), code=400)
    except Exception as e:
        logger.error(f"用户注册失败，系统错误: {str(e)}")
        logger.exception("注册失败的完整堆栈信息")
        return ResponseFactory.error(msg='注册失败，请稍后重试', code=500)


@users_bp.route('/login', methods=['POST'])
def login():
    """用户登录
    
    Returns:
        JSON格式的用户信息和访问令牌
    """
    logger.info("收到用户登录请求")
    data = request.get_json()
    
    # 验证请求数据
    if not data or 'username' not in data or 'password' not in data:
        logger.warning("登录请求数据不完整，缺少用户名或密码")
        return ResponseFactory.error(msg='用户名和密码是必填项', code=400)
    
    username = data['username']
    password = data['password']
    
    logger.info(f"用户登录尝试，用户名/邮箱: {username}")
    
    try:
        # 验证用户身份
        user = user_service.authenticate_user(username, password)
        
        if not user:
            logger.warning(f"用户登录失败，用户名/邮箱: {username}")
            return ResponseFactory.error(msg='用户名或密码错误', code=401)
        
        # 创建JWT访问令牌
        access_token = create_access_token(identity=str(user.id))
        
        logger.info(f"用户登录成功，用户ID: {user.id}, 用户名: {user.username}")
        
        return ResponseFactory.success(data={
            'access_token': access_token,
            'user': user_schema.dump(user)
        }, msg='登录成功')
        
    except Exception as e:
        logger.error(f"用户登录失败，系统错误: {str(e)}")
        logger.exception("登录失败的完整堆栈信息")
        return ResponseFactory.error(msg='登录失败，请稍后重试', code=500)


@users_bp.route('/forgot-password', methods=['POST'])
def forgot_password():
    """忘记密码
    
    Returns:
        JSON格式的成功消息
    """
    data = request.get_json()
    
    # 创建验证器
    forgot_schema = ForgotPasswordSchema()
    
    # 验证数据
    errors = forgot_schema.validate(data)
    if errors:
        return ResponseFactory.error(msg='数据验证失败', code=400, errors=errors)
    
    try:
        # 处理忘记密码请求
        success = user_service.forgot_password(data['email'])
        
        if success:
            return ResponseFactory.success(msg='如果该邮箱已注册，您将收到重置密码的邮件')
        else:
            return ResponseFactory.error(msg='处理失败，请稍后重试', code=500)
            
    except Exception as e:
        return ResponseFactory.error(msg='处理失败，请稍后重试', code=500)
